package com.xy.project.lhyz;

import cn.hutool.core.util.IdUtil;
import com.xy.core.annotation.RegisterServer;
import com.xy.core.constant.FnKit;
import com.xy.etl.ds.model.DataSourceConfig;
import com.xy.etl.ds.strategy.InsertBuilder;
import com.xy.etl.kit.ClientHelper;
import com.xy.etl.kit.EtlDao;
import com.xy.etl.kit.IEtlServer;
import com.xy.etl.opc.OpcDao;
import com.xy.etl.service.YmlConfig;
import com.xy.project.lhyz.config.SelfOpcConfig;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * 固定时间间隔（1s）
 */
@Slf4j
@RegisterServer("opc1Server")
public class Opc1Server implements IEtlServer {
    @Resource
    private YmlConfig yml;
    /**
     * opc配置
     */
    private SelfOpcConfig opcConfig;
    /**
     * 保存库配置
     */
    private DataSourceConfig dataSourceConfig;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() throws Exception {
        opcConfig = yml.getProperty("etl.opc1", new SelfOpcConfig());
        opcConfig.init();
        dataSourceConfig = yml.getProperty("etl.dest", new DataSourceConfig());
    }

    /**
     * 作业周期（单位秒），默认10s
     *
     * @return
     */
    public Integer getIntervalSecond() {
        return Integer.valueOf(opcConfig.getInterval());
    }


    /**
     * 处理
     */
    public void process() {
        Long start = System.currentTimeMillis();
        Long start2 = System.currentTimeMillis();
        //检查数据库连接有效性
        ClientHelper.checkConn();
        log.info("************************采集显示器开始");
        try {
            String clasz = this.getClass().getSimpleName();
            Map<String, Object> opcValueMap = null;
            try {
                opcValueMap = OpcDao.readOpcValue(opcConfig, opcConfig.getOpcKeyList(), clasz);
            } catch (Exception ex) {
                String msg = ex.getMessage();
                if (msg == null) {
                    msg = "";
                }
                if (msg.indexOf("Bad_Timeout") >= 0) {
                    log.error("OPC读取keyList:{}连接超时，退出", FnKit.join(opcConfig.getOpcKeyList()));
                } else {
                    log.error(msg, ex);
                }
                return;
            }

            log.info("OPC读取：{}耗时：{}", FnKit.join(opcConfig.getOpcKeyList()), (System.currentTimeMillis() - start2));
            if (opcValueMap == null || opcValueMap.size() == 0) {
                log.info("没有查询到opc数据，直接完成");
                return;
            }
            Date now = new Date();
            for (Map.Entry<String, Object> entry : opcValueMap.entrySet()) {
                try {
                    log.info("----" + entry.getKey() + ":" + entry.getValue());
                    InsertBuilder insert = new InsertBuilder("prod_opc_data").setReplace(false);
                    insert.newLine();
                    insert.set("id", IdUtil.getSnowflake(1, 2).nextId());
                    insert.set("business_type", opcConfig.getType());
                    insert.set("business_key", opcConfig.getKey(entry.getKey()));
                    insert.set("business_value", entry.getValue().toString());
                    insert.set("create_time", now);
                    insert.set("create_user", 10203);
                    insert.set("is_deleted", 0);
                    insert.set("tenant_id", opcConfig.getTenantId());
                    EtlDao.run(insert.build(), dataSourceConfig);
                } catch (Exception ex2) {
                    log.error(ex2.getMessage(), ex2);
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            log.info("************************采集显示器结束，总耗时：{}", System.currentTimeMillis() - start);
        }
    }
}
